package friend

import (
	"api/common"
	"api/pb/friend"
	"api/pb/user"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFriendRelationListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetFriendRelationListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFriendRelationListLogic {
	return &GetFriendRelationListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetFriendRelationList 获取好友列表
func (l *GetFriendRelationListLogic) GetFriendRelationList(req *types.FriendRelationListRequest) (resp *types.FriendRelationListResponse, err error) {
	userID, err := common.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}
	// 获取好友列表
	result, err := l.svcCtx.FriendRPC.GetRelationList(l.ctx, &friend.RelationListRequest{
		UserId: userID, GroupId: req.GroupID, Status: req.Status, Offset: req.Offset, Limit: req.Limit,
	})

	if err != nil {
		return nil, err
	}
	resp = &types.FriendRelationListResponse{
		Total: result.Total,
		Data:  make([]types.FriendRelationInfo, 0),
	}
	// 构造id列表
	friendIDList := make([]int64, 0)
	for _, item := range result.Data {
		friendIDList = append(friendIDList, item.FriendId)
	}
	// 获取id对应名字
	nameResult, err := l.svcCtx.UserRPC.GetUserListByIDs(l.ctx, &user.UserListByIDsRequest{Ids: friendIDList})
	if err != nil {
		return nil, err
	}
	nameMap := make(map[int64]string)
	for _, item := range nameResult.Data {
		nameMap[item.Id] = item.Name
	}
	// 填充数据
	for _, item := range result.Data {
		resp.Data = append(resp.Data, types.FriendRelationInfo{
			ID: item.Id, UserID: item.UserId, FriendID: item.FriendId, FriendName: nameMap[item.FriendId],
		})
	}
	return resp, nil
}
